package com.qfedu.fmmall.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qfedu.fmmall.vo.ResStatus;
import com.qfedu.fmmall.vo.ResultVO;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Token的拦截器
 */
@Component
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        // 判断是否是第一次的预检请求
        if ("OPTIONS".equalsIgnoreCase(method)) {
            return true;
        }
        // 获取token
        String token = request.getHeader("token");
        System.out.println("进入拦截器！");
        if (token == null) {
            // 提示请先登录
            ResultVO vo = new ResultVO(ResStatus.NO.getCode(), "请先登录", null);
            doResponse(response, vo);
        } else {
            try {
                JwtParser parser = Jwts.parser();
                parser.setSigningKey("123456");//解析token的signingkey必须和生成token时设置的密码相同
                // 如果token正确（密码正确，有效期内）
                Jws<Claims> claimsJws = parser.parseClaimsJws(token);
                return true;
            } catch (ExpiredJwtException e) {
                // 提示登录过期
                ResultVO vo = new ResultVO(ResStatus.NO.getCode(), "登录过期，请重新登录", null);
                doResponse(response, vo);
            } catch (UnsupportedJwtException e) {
                ResultVO vo = new ResultVO(ResStatus.NO.getCode(), "token不合法", null);
                doResponse(response, vo);
            } catch (Exception e) {
                ResultVO vo = new ResultVO(ResStatus.NO.getCode(), "登录失败", null);
                doResponse(response, vo);
            }
        }
        return false;
    }

    private void doResponse(HttpServletResponse response, ResultVO vo) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(vo);
        out.print(s);
        out.flush();
        out.close();
    }
}
